/*
 * @Descripttion:
 * @version:
 * @Author: ChenXiang
 * @Date: 2021-03-29 11:02:14
 * @LastEditors: ChenXiang
 * @LastEditTime: 2021-03-31 13:34:48
 */
"use strict";
require("./check-versions")();

process.env.NODE_ENV = "production";
process.env.BUILD_MODE = "";

const ora = require("ora");
const rm = require("rimraf");
const path = require("path");
const chalk = require("chalk");
const webpack = require("webpack");
const config = require("../config/webpack");
const webpackDllConfig = require("./webpack.dll");

const buildtype = process.argv.slice(2)[0] || "development";
console.log(process.argv);

const spinner = ora("构建中..." + buildtype + ".....");
spinner.start();

function buildDll() {
  return new Promise((resolve, reject) => {
    webpack(webpackDllConfig, (err, stats) => {
      spinner.stop();
      if (err) throw err;
      process.stdout.write(
        stats.toString({
          colors: true,
          modules: false,
          children: false, // If you are using ts-loader, setting this to true will make TypeScript errors show up during build.
          chunks: false,
          chunkModules: false,
        }) + "\n\n"
      );

      if (stats.hasErrors()) {
        console.log(chalk.red("构建Dll失败.\n"));
        reject();
        process.exit(1);
      }
      console.log(chalk.cyan("构建DLL完成.\n"));
      resolve();
    });
  });
}

function buildProject(config) {
  return new Promise((resolve, reject) => {
    webpack(config, (err, stats) => {
      spinner.stop();
      if (err) throw err;
      process.stdout.write(
        stats.toString({
          colors: true,
          modules: false,
          children: false, // If you are using ts-loader, setting this to true will make TypeScript errors show up during build.
          chunks: false,
          chunkModules: false,
        }) + "\n\n"
      );

      if (stats.hasErrors()) {
        console.log(chalk.red("项目构建失败.\n"));
        reject();
        process.exit(1);
      }

      console.log(chalk.cyan("项目构建完成.\n"));
      resolve();
    });
  });
}

rm(
  path.join(config.build.assetsRoot, config.build.assetsSubDirectory),
  (err) => {
    if (err) throw err;
    console.log("buildtype", buildtype);
    if (buildtype === "online") {
      buildDll()
        .then(() => {
          return require("./webpack.prod");
        })
        .then(function (config) {
          return buildProject(config);
        });
    } else {
      buildDll()
        .then(() => {
          return require("./webpack.test");
        })
        .then(function (config) {
          return buildProject(config);
        });
    }
  }
);
